/**
 * Created by James on 14-3-16.
 */
var sqlclient = module.exports;

var _pool;

var NND = {};


//初始化sql连接池
//@param{Object} app the app for the server

NND.init = function(app){
    _pool = require('./pool').createMysqlPool(app);
};


NND.query = function(sql, args, cb){
    _pool.acquire(function(err, client){
        if(!!err){
            console.error('[sqlqueryErr] '+err.stack);
            return;
        }
        client.query(sql, args, function(err, res){
            _pool.release(client);
            cb(err, res);
        });
    });
};

//关闭连接池
NND.shutdown = function(){
    _pool.destoryAllNow();
}

//初始化数据库
sqlclient.init = function(app){
    if(!!_pool){
        return sqlclient;
    }else {
        NND.init(app);
        sqlclient.insert = NND.query;
        sqlclient.update = NND.query;
        sqlclient.delete = NND.query;
        sqlclient.query = NND.query;
        return sqlclient;
    }
}

//关闭数据库
sqlclient.shutdown = function(app) {
    NND.shutdown(app);
};